package com.mall.web.control.eshop;

import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.mall.biz.eshop.TransferAuditBizImpl;
import com.mall.biz.user.UserBizImpl;
import com.mall.biz.user.VerifyCodeBizImpl;
import com.mall.client.commkey.CommKeyService;
import com.mall.client.eshop.TransferAuditService;
import com.mall.client.user.SessService;
import com.mall.client.user.UserExtendedService;
import com.mall.client.user.UserService;
import com.mall.common.Consts.PassJiaMi;
import com.mall.common.util.MD5Util;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.common.util.token.TokenUtils;
import com.mall.constant.PropertiesKey;
import com.mall.constant.ReqAttributeKey;
import com.mall.enums.RegionEnum;
import com.mall.pojo.Commkey;
import com.mall.pojo.Sess;
import com.mall.pojo.TransferAudit;
import com.mall.pojo.User;
import com.mall.pojo.UserExtended;
import com.mall.query.eshop.TransferAuditQuery;
import com.mall.vo.user.AliTonghua;
import com.mall.vo.user.UserVO;
import com.mall.web.annotation.EShopUserSecurity;
import com.mall.web.util.AliBaiChuanUtil;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.MaiGeDianWebUtil;
import com.mall.web.util.WebUtil;
import com.mall.web.vo.ResponseEntity;
/**
 * 用户登录注册等一系列用户操作
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/eshop/user/")
public class EShopUserController {

	private Logger log = LoggerFactory.getLogger(EShopUserController.class);

	public final int ESHOP_COMMON_ONLY_KEY = 2;

	@Autowired
	private UserBizImpl userBiz;
	@Autowired
	private UserExtendedService userExtendedService;
	@Autowired
	private UserService userService;
	@Autowired
	private VerifyCodeBizImpl verifyCodeBiz;
	@Autowired
	private PropertiesConfigure propertiesConfigure;
	@Autowired
	private CommKeyService commKeyService;
	@Autowired
	private SessService sessService;
	@Autowired
	private TransferAuditService transferAuditService;
	@Autowired
	private TransferAuditBizImpl transferAuditBizImpl;
	@Autowired
	private VerifyCodeBizImpl verifyCodeBizImpl;
	
	
	
	private final String USERPNG = "user/nan.png";
	@RequestMapping("eshopxieyi")
	public String eshopxieyi(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		return "eshop/eshopxieyi";
	}

	@RequestMapping("eshoplogin")
	public String eshoplogin(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		//Integer onlyKey = ESHOP_COMMON_ONLY_KEY;
		String referer = HttpUtil.getHttpReferer(request);
		//modelMap.put("onlyKey", onlyKey);
		modelMap.put("referer", referer);
		return "eshop/eshoplogin";
	}
	
	/**
	 * pc端登录
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("pcEshopLogin")
	public String pcEshopLogin(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String referer = HttpUtil.getHttpReferer(request);
		modelMap.put("rdeferer", referer);
		return "eshop/pcEshopLogin";
	}

	/**
	 * 注册
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("eshopregister")
	public String eshopregister(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		//Integer onlyKey = ESHOP_COMMON_ONLY_KEY;
		//modelMap.put("onlyKey", onlyKey);
		return "eshop/eshopregister";

	}

	@RequestMapping("eshoploginAction")
	@ResponseBody
	public ResponseEntity<UserVO> loginAction(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		String deviceToken = request.getParameter("deviceToken");
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();

		UserVO userVO = this.userBiz.login(request.getParameter("phone"), request.getParameter("passWord"),
				ESHOP_COMMON_ONLY_KEY);// 用户手机号登陆
		if (userVO == null) {
			responseEntity.initErrorResponseEntity(null, "账号或密码错误");
			return responseEntity;
		}
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(userVO.getUser().getId());
		String userDeviceToken = null;
		if(userExtended != null){
			userExtended.getDeviceToken();
		}
		
		if (StringUtils.isNotBlank(userDeviceToken) && StringUtils.isNotBlank(deviceToken)) {
			if (!userDeviceToken.equals(deviceToken)) {// deviceToken不同时候更新
				userVO.setUserExtended(userExtended);
				/**
				 * 用户登陆更新app对应的deviceToken
				 */
				Boolean updateyoumengDeviceToken = this.userBiz.updateDeviceToken(userVO,
						request.getParameter("deviceToken"));
				log.info("更新deviceToken", updateyoumengDeviceToken);
			}
		}

		Boolean sessResult = userBiz.updateOrInsertSess(request, response, userVO, ESHOP_COMMON_ONLY_KEY);
		log.info("更新session", sessResult);
		if (!sessResult) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("sess insert or update error");
			return responseEntity;
		}
		responseEntity.initSuccResponseEntity(userVO, "login success");
		return responseEntity;
	}
	
	/**
	 * pc端登录action
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("pcEshoploginAction")
	@ResponseBody
	public ResponseEntity<UserVO> pcLoginAction(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();

		UserVO userVO = this.userBiz.login(request.getParameter("phone"), request.getParameter("passWord"),
				ESHOP_COMMON_ONLY_KEY);// 用户手机号登陆
		if (userVO == null) {
			responseEntity.initErrorResponseEntity(null, "账号或密码错误");
			return responseEntity;
		}

		Boolean sessResult = userBiz.updateOrInsertSess(request, response, userVO, ESHOP_COMMON_ONLY_KEY);
		log.info("更新session", sessResult);
		if (!sessResult) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("sess insert or update error");
			return responseEntity;
		}
		responseEntity.initSuccResponseEntity(userVO, "login success");
		return responseEntity;
	}

	@RequestMapping("eshopregisterAction")
	@ResponseBody
	public ResponseEntity<UserVO> eshopregisterAction(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		Integer onlyKey = ESHOP_COMMON_ONLY_KEY;
		ResponseEntity<UserVO> responseEntity = new ResponseEntity<>();

		String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone").trim();
		String valid = request.getParameter("valid") == null ? "" : request.getParameter("valid").trim();// 验证码

		String deviceToken = request.getParameter("deviceToken");// 手机对应型号
		if (StringUtils.isBlank(phone) || StringUtils.isBlank(valid)) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("注册失败");
			return responseEntity;
		}

		User userPhone = this.userService.getUserByPhone(phone, onlyKey);// 校验手机号是否注册过
		if (userPhone != null) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("phone and password is error");
			return responseEntity;
		}

		boolean verifyCode = verifyCodeBiz.checkVerifyCode(phone, valid);// 校验验证码
		if (verifyCode == false) {
			responseEntity.setCode("-400");
			responseEntity.setData(null);
			responseEntity.setMessage("inviteCode is error");
			return responseEntity;
		}
		String passWord = request.getParameter("passWord");
		passWord = passWord.trim();
		UserVO userVO = new UserVO();
		Date createTime = new Date();
		User user = new User();
		user.setPassword(getPassWordMd5(passWord, phone));// 注册时密码不需要校验吗？还需要md5加密
		user.setPortrait(USERPNG);
		user.setPhone(phone);
		user.setUserName(phone);
		user.setNameAndPhone(phone + phone);
		/**
		 * 根据onlykey存对应的省市区
		 */
		List<Commkey> commKeyList = this.commKeyService.getComKeyByCommOnlyKey(onlyKey);
		user.setCommOnlyKey(onlyKey);
		user.setProvinceId(commKeyService.getRegionByList(RegionEnum.PROVINCE.getCode(), commKeyList));
		user.setCityId(commKeyService.getRegionByList(RegionEnum.CITY.getCode(), commKeyList));
		user.setAreaId(commKeyService.getRegionByList(RegionEnum.AREA.getCode(), commKeyList));
		userVO.setUser(user);

		/**
		 * 用户阿里百川存入数据库
		 */
		String aliUserId = AliBaiChuanUtil.UID + phone;
		String aliPass = AliBaiChuanUtil.PASS;
		AliTonghua aliTonghua = new AliTonghua(aliUserId, aliPass);
		UserExtended userExtended = new UserExtended();
		userExtended.setAliTongxun(JSONArray.toJSONString(aliTonghua));
		userExtended.setAliTongxueId(aliUserId);
		userExtended.setDeviceToken(deviceToken);
		userVO.setUserExtended(userExtended);
		this.userService.register(userVO, createTime);
		/**
		 * 用户注册到阿里百川
		 */
		boolean insertResult = AliBaiChuanUtil.insertUserInfoAliBaiChuan(user);
		log.error("插入用户到阿里百川" + insertResult);

		Boolean sessResult = userBiz.updateOrInsertSess(request, response, userVO, onlyKey);
		log.info("更新session", sessResult);
		if (!sessResult) {
			responseEntity.setCode("-500");
			responseEntity.setData(null);
			responseEntity.setMessage("sess insert or update error");
		}

		String userImgUrl = propertiesConfigure.getProperties(PropertiesKey.userfilepath);
		userVO.setImgBeiginUrl(userImgUrl);
		String token = TokenUtils.getToken(userVO.getUser().getId(), user.getPassword(), new Date());
		userVO.setToken(token);
		userVO.setSessionID(WebUtil.getUserCookieValue(request));

		responseEntity.initSuccResponseEntity(userVO, "注册成功");

		return responseEntity;

	}

	private String getPassWordMd5(String passWord, String phone) {
		return MD5Util.GetMD5Code(passWord, phone + "", PassJiaMi.MD5JIAYAN);
	}
	
	
	/**
	 * 退出登录
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("signoutAction")
	@ResponseBody
	@EShopUserSecurity
	public ResponseEntity<String> signoutAction(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		request.removeAttribute(ReqAttributeKey.CURRENT_LOGIN_USER);
		request.getSession().removeAttribute(ReqAttributeKey.CURRENT_LOGIN_USER);
		Cookie cookie = new Cookie("juid",null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		String juid = getJUID(request);
		List<Sess> sessList = this.sessService.getListBySessionKeyAndUserId(juid, user.getId(), onlyKey);
		if(sessList != null && sessList.size() > 0){
			for(Sess sess : sessList){
				sess.setGmtModify(new Date());
				sess.setStatus(-4);
				this.sessService.updateSess(sess);
			}
		}
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("sign out success");
		return responseEntity;
	}
	
	private String getJUID(HttpServletRequest request){
		String cookieValue = "";
		Cookie[] cookies = request.getCookies();//从request获得cookie数组
		if(cookies == null){
			return "";
		}
		for(Cookie cookie : cookies){
			if(cookie.getName().equalsIgnoreCase("JUID")){
				cookieValue = cookie.getValue();
				return cookieValue;
			}
		}
		return cookieValue;
	}
	
	
	//----------------------------------以下用户操作---------------------------------------
	
	/**
	 * 点击充值进入充值中心
	 */
	@RequestMapping("eshopRecharge")
	@EShopUserSecurity
	public String eshopRecharge(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(user.getId());
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		//判断是否有审核中的转账信息
		List<TransferAudit> transferAuditList = this.transferAuditService.getTransferAuditListByUserAndKey(user.getId(), onlyKey, 0,user.getPhone());
		modelMap.put("user", user);
		modelMap.put("userExtended", userExtended);
		modelMap.put("transferAuditList", transferAuditList);
		return "eshop/eshopRecharge";
	}
	
	/**
	 * 提交转账信息
	 */
	@RequestMapping("uploadTransferAuditAction")
	@ResponseBody
	@EShopUserSecurity
	public ResponseEntity<String> uploadTransferAuditAction(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Integer type = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "type", 0);//0账户充值
		String transferRemark = HttpUtil.getStringValueFromRequest(request, "transferRemark");//转账备注,多少钱
		String transferVoucher = HttpUtil.getStringValueFromRequest(request, "transferVoucher");//转账账号
		if(StringUtils.isBlank(transferRemark) || StringUtils.isBlank(transferVoucher)){
			responseEntity.initErrorResponseEntity(null, "资料不齐");
			return responseEntity;
		}
		TransferAudit transferAudit = new TransferAudit();
		transferAudit.setCommOnlyKey(onlyKey);
		transferAudit.setMallId(1l);
		transferAudit.setUserId(user.getId());
		transferAudit.setPhone(user.getPhone());
		transferAudit.setStatus(0);
		transferAudit.setTransferRemark(transferRemark);
		transferAudit.setTransferVoucher(transferVoucher);
		transferAudit.setType(type);
		this.transferAuditService.insertTransferAudit(transferAudit);
		responseEntity.initSuccResponseEntity(null, "提交成功");
		String content = "";
		if(type == 0){
			content = "用户："+user.getUserName()+"  手机："+user.getPhone()+"提交了支付宝转账￥"+transferRemark;
		}else if (type == 1){
			content = "用户："+user.getUserName()+"  手机："+user.getPhone()+"提交了银行卡转账￥"+transferRemark;
		}
		this.verifyCodeBizImpl.sendMessToMaigedianManager(MaiGeDianWebUtil.caiwuPhone,content);
		return responseEntity;
	}
	
	/**
	 * 转账信息列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	
	@RequestMapping("transferRecordList")
	@EShopUserSecurity
	public String transferRecordList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		transferRecordModelMap(request,response,modelMap);
		return "eshop/transferRecordList";
	}
	
	/**
	 * 转账信息列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("transferRecordMore")
	@EShopUserSecurity
	public String transferRecordListMore(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		transferRecordModelMap(request,response,modelMap);
		return "weishang/supplier/transferRecordMore";
	}
	
	private ModelMap transferRecordModelMap(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		/*Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize",PageUtil.PAGE_SIZE_APP);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);*/
		
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		
		TransferAuditQuery transferAuditQuery = new TransferAuditQuery();
		//transferAuditQuery.setPage(page);
		transferAuditQuery.setOnlyKey(onlyKey);
		transferAuditQuery.setOrderBy("gmt_create desc");
		transferAuditQuery.setUserId(user.getId());
		
		List<TransferAudit> transferAuditList = this.transferAuditBizImpl.getTransferAuditListByQuery(transferAuditQuery);
		
		//modelMap.put("pageNo", pageNo);
		//modelMap.put("pageSize", pageSize);
		modelMap.put("transferAuditList", transferAuditList);
		modelMap.put("user", user);
		return modelMap;
	}
	
	
}
